package com.ran.providermodule.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by ran on 2017/10/15.
 */

public class DbDao implements InsertInter {
    private static final String TAG = DbDao.class.getSimpleName();
    private static DbHelper dbHelper;
    private static volatile DbDao instance = null;
    private static SQLiteDatabase sqLiteDatabase;

    private DbDao() {
    }

    public static synchronized DbDao getInstance(Context context) {
        if (instance == null) {
            synchronized (DbDao.class) {
                if (instance == null) {
                    instance = new DbDao();
                    dbHelper = new DbHelper(context, DbConfig.DB_NAME, null, DbConfig.DB_BASE_VERSION);
                }
            }
        }
        sqLiteDatabase = dbHelper.getReadableDatabase();
        return instance;
    }

    @Override
    public void insert(List<Bean> beanList) {
        Log.d(TAG,"insert() excuted...");
        Log.d(TAG,"start:"+time());
        String sql = "insert into test(id,name,address,age,height,phone) values(?,?,?,?,?,?)";
        try {
            SQLiteStatement sstatement = sqLiteDatabase.compileStatement(sql);
            sqLiteDatabase.beginTransaction();
            for (Bean bean : beanList) {
                sstatement.bindLong(1, bean.getId());
                sstatement.bindString(2, bean.getName());
                sstatement.bindString(3, bean.getAddress());
                sstatement.bindLong(4, bean.getAge());
                sstatement.bindLong(5, bean.getHeight());
                sstatement.bindLong(6, bean.getPhone());
                sstatement.executeInsert();
                Log.d(TAG,bean.toString());
            }
            sqLiteDatabase.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqLiteDatabase.endTransaction();
            sqLiteDatabase.close();
            Log.d(TAG,"end:"+time());
        }
    }

    public String time(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }
}
